package movee.io.dunet;

import feign.RequestInterceptor;
import feign.Retryer;
import org.springframework.context.annotation.Bean;
import org.springframework.util.DigestUtils;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 *
 *
 * @author movee
 */
public class DunetFeignConfig {

    /**
     * 自定义重试机制
     * @return Retryer
     */
    @Bean
    public Retryer feignRetryer() {
        // 最大请求次数为2，初始间隔时间为100ms，下次间隔时间1.5倍递增，重试间最大间隔时间为1s，
        return new Retryer.Default(100, SECONDS.toMillis(1), 2);
    }

    /**
     * fegin 拦截器
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            String appName = DunetConfig.appName;
            String token = DunetConfig.token;
            requestTemplate.header("app-name", appName);
            long currentTime = System.currentTimeMillis();
            requestTemplate.header("time-stamp", Long.toString(currentTime));
            String authText = appName + currentTime + token;
            String auth = DigestUtils.md5DigestAsHex(authText.getBytes()).toLowerCase();
            requestTemplate.header("Authorization", auth);
            requestTemplate.header("Content-Type", "application/json");
            requestTemplate.header("Accept", "application/json");
        };
    }
}
